import moment from 'moment'
import _ from 'lodash'
import axios from 'axios'

function getAuth(p) {
  return new Promise((resolve, reject) => {
    axios
      .get('https://nb-oa.lianlianlvyou.com/v2/wx/auth?platForm=' + p)
      .then((res) => {
        if (res.errMessage) {
          return reject(res.errMessage)
        }
        resolve(res.data)
      })
      .catch((e) => {
        reject(e)
      })
  })
}
export default {
  install(Vue, options) {
    Vue.prototype.paramIsNull = function(param) {
      if (typeof param === 'undefined' || param === null || param === 'undefined' || param === 'null') {
        return true
      } else if (param instanceof Array) {
        return param.length === 0
      } else if (typeof param === 'string') {
        return param.replace(/(^\s*)|(\s*$)/g, '').length === 0
      }
      return false
    }
    Vue.prototype.paramIsNullAndZero = function(param) {
      if (typeof param === 'undefined' || param === null) {
        return true
      } else if (typeof param === 'number' && param === 0) {
        return true
      }
      return false
    }
    Vue.prototype.pro_dateFormat = function(param, format) {
      if (typeof param === 'undefined' || param === null) {
        return ''
      } else {
        return moment(param).format(format)
      }
    }
    Vue.prototype.pro_yyyyMMDDHHmmss = function(val) {
      if (typeof val === 'undefined' || val === null) {
        return ''
      } else {
        return moment(val).format('YYYY-MM-DD HH:mm:ss')
      }
    }
    Vue.prototype.pro_yyyyMMDD = function(val) {
      if (typeof val === 'undefined' || val === null || (val instanceof Date && isNaN(val.valueOf()))) {
        return ''
      } else {
        return moment(val).format('YYYY-MM-DD')
      }
    }
    Vue.prototype.weekFormat = function(value) {
      if (typeof value !== 'undefined' && value !== null) {
        var date = new Date(value)
        var week = ''
        var weekDay = date.getDay()
        switch (weekDay) {
          case 0:
            week = '星期日'
            break
          case 1:
            week = '星期一'
            break
          case 2:
            week = '星期二'
            break
          case 3:
            week = '星期三'
            break
          case 4:
            week = '星期四'
            break
          case 5:
            week = '<p style="color: red;">星期五</p>'
            break
          case 6:
            week = '<p style="color: red;">星期六</p>'
            break
        }
        return week
      } else {
        return ''
      }
    }
    Vue.prototype.pro_isWechatClient = function() {
      var ua = window.navigator.userAgent.toLowerCase()
      var str = ua.match(/MicroMessenger/i)
      return !this.paramIsNull(str)
    }
    Vue.prototype.pro_wechatOpenAppId = function() {
      return getAuth(1)
      // return 'wx7589d03c1e49f4ba'
    }
    Vue.prototype.pro_wechatAppId = function() {
      return getAuth(2)
      // return 'wx3ed1ccc70f9740b4'
    }
    Vue.prototype.pro_addQueryString = function(url, name, value) {
      let currentUrl = url.split('#')[0]
      if (/\?/g.test(currentUrl)) {
        if (/name=[-\w]{4,25}/g.test(currentUrl)) {
          currentUrl = currentUrl.replace(/name=[-\w]{4,25}/g, name + '=' + value)
        } else {
          currentUrl += (currentUrl.endsWith('?') ? '' : '&') + name + '=' + value
        }
      } else {
        currentUrl += '?' + name + '=' + value
      }
      if (url.split('#')[1]) {
        return currentUrl + '#' + url.split('#')[1]
      } else {
        return currentUrl
      }
    }
    Vue.prototype.pro_deleteQueryString = function(url, name) {
      let reg = new RegExp('(|&)' + name + '=([^&/#]*)')
      let str = url.match(reg)
      if (str && str[0]) {
        let newurl = url.replace(str[0], '')
        return newurl.replace('?&', '?').replace('?#', '#')
      }
      return url
    }
    Vue.prototype.pro_getQueryString = function(name) {
      let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
      if (window.location.search.indexOf('=') > -1) {
        let r = window.location.search.substr(1).match(reg)
        if (r) {
          return unescape(r[2])
        }
      }
      return ''
    }
    Vue.prototype.pro_message_error = function(code, error) {
      if (code === 404) {
        this.$messageSend.error('请求资源不存在')
        return
      }
      this.$messageSend.error(error)
    }
    Vue.prototype.pro_message_info = function(message) {
      this.$messageSend.info(message)
    }
    Vue.prototype.pro_message_success = function(success) {
      this.$messageSend.success(success)
    }
    Vue.prototype.pro_request_url_filter = function(request) {
      var urlArray = ['/v2/user/overtime/wechat/login']
      var url = request.url
      if (this.paramIsNull(url)) {
        return false
      }
      var end = url.indexOf('?')
      if (end > 0) {
        url = url.substring(0, url.indexOf('?'))
      }
      if (urlArray.indexOf && typeof urlArray.indexOf === 'function') {
        if (urlArray.indexOf(url) >= 0) {
          return false
        }
      }
      return true
    }
    // 检查文件大小，默认不超过2M
    Vue.prototype.$limitSize = function(file, fileList, limitSize = 2) {
      const rawFile = file.raw || file
      const isRegular = rawFile.size < 1024 * 1024 * limitSize
      if (!isRegular) {
        this.$messageSend.error(`文件大小不能超过${limitSize}M!`)
        fileList.pop && fileList.pop()
      }
      return isRegular
    }

    Vue.prototype.$handleSuccess = function(res, file, fileList) {
      if (res && res[0]) {
        // 上传成功
        let url = res[0]
        let item = _.find(fileList, (e) => e.url === file.url)
        if (item) item.url = url
        return fileList
      } else {
        let msg = res.errMessage || '图片上传失败，已删除'
        this.$messageSend.error(msg)
        let i = _.findIndex(fileList, (e) => e.url === file.url)
        fileList.splice(i, 1)
        return fileList
      }
    }
  }
}
